package com.cinema.web;

import com.cinema.dao.SeatDao;
import com.cinema.entity.*;
import com.cinema.service.HallService;
import com.cinema.service.OrderService;
import com.cinema.service.SeatService;
import com.cinema.util.HttpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping(value = "/seat")
public class SeatController {
    @Autowired
    private SeatService seatService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private HallService hallService;
    @RequestMapping("/controlseat")
    @ResponseBody
    private Map<String,Object> insertSeat(HttpServletRequest request){
        Map<String,Object> modelMap = new HashMap<>();
        //获取前端传入的hallId和座位号
        int hallId = HttpUtil.getInt(request,"hallId");
        int seatSerialNumber = HttpUtil.getInt(request,"seatSerialNumber");
        //判断此座位是否被占
        int effectedNum = seatService.boolSeat(hallId,seatSerialNumber);
        //没被占的话，插入座位数据
        if (effectedNum > 0){
            Seat seat = new Seat();
            Hall hall = new Hall();
            hall.setHallId(hallId);
            seat.setHall(hall);
            seat.setSeatSerialNumber(seatSerialNumber);
            seat.setWhetherEmpty("true");
            seat.setCreateTime(new Date());
            seat.setLastEditTime(new Date());
            int ans = seatService.insertSeat(seat);
            if (ans > 0){
                //插入成功的话
                modelMap.put("success",true);
                //获取对应电影信息
                Hall hall1 = new Hall();
                hall.setHallId(hallId);
                Film film = hallService.queryFilmByHallId(hallId);
                //获取用户信息
                User user = new User();
                user.setUserId((Integer) request.getSession().getAttribute("userId"));
                //建立订单信息
                Ordering ordering = new Ordering();
                ordering.setHall(hall);
                ordering.setFilm(film);
                ordering.setSeat(seat);
                ordering.setUser(user);
                ordering.setCreateTime(new Date());
                ordering.setLastEditTime(new Date());
                orderService.insertOrder(ordering);
            }else {
                modelMap.put("success",false);
                modelMap.put("errMsg","系统错误");
            }
        }else {
            modelMap.put("success",false);
        }
        return modelMap;
    }
}
